import {
  getStandFileInfoByPage,
  addStandFileInfo,
  uploadStandFileInfoDrawing,
  uploadStandFileInfoBom,
  delStandFileInfo,
  exportStandFileInfo,
  getProductTypeList,
  getStandFileType,
  downloadFile,
  getStandFileInfoByStandTypeIdAndCategoryPage,
  switchStandFileInfo,
} from '@/services/design/standFileInfo';
import { downloadStandardBom } from '@/services/design/productBomOverview';
import {
  PlusOutlined,
  UploadOutlined,
  ArrowLeftOutlined,
  DownloadOutlined,
} from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import {
  Button,
  Form,
  Input,
  message,
  Modal,
  Tree,
  Select,
  Upload,
  Descriptions,
  Row,
  Col,
} from 'antd';
import { sortTran, filterTran, filterTranNew } from '@/utils/requestUtil';
import React, { useEffect, useRef, useState } from 'react';
import { history } from 'umi';
import { bom_downloadFile } from '@/services/design/standProduct';
import { values } from 'lodash';
const StandFileInfoBOM: React.FC<{}> = (props) => {
  const actionRef = useRef<ActionType>();
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable
  const [formTitle, setFormTitle] = useState('新建'); //
  const [createOrUpdate, setCreateOrUpdate] = useState(false); //编辑框的disable
  const [file, setFile] = useState();
  const [category, setcategory] = useState();
  const [optionsTypeDesc, setoptionsTypeDesc] = useState([]); //下拉框用到
  const [optionsstandfile, setoptionsstandfile] = useState([]);
  const [bomisuse, setbomisuse] = useState(false); //判断是否有正在启用的BOM
  StandFileInfoBOM.defaultProps = {
    thisstandTypeCode: '',
    thisstandTypeDesc: '',
    thisstandid: '',
    thisstandname: '',
    thisstate: '',
  };
  const thisstandTypeCode = props.thestandTypeCode;
  const thisstandTypeDesc = props.thestandTypeDesc;
  const thisstandid = props.thestandid;
  const thisstandname = props.thestandname;
  const thisstate = props.thestate;

  const [form] = Form.useForm();
  const ref = useRef(null);
  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 60,
      align: 'center',
      sorter: true,
    },
    // {
    //   title: '柜体类型',
    //   dataIndex: 'standTypeDesc',
    // },
    // {
    //   title: '柜体编号',
    //   dataIndex: 'standTypeCode',
    // },
    // {
    //   title: '柜体名称',
    //   dataIndex: 'standTypeName',
    // },

    {
      title: '文件类别',
      dataIndex: 'category',
      align: 'center',
      sorter: true,

      width: 100,
    },
    {
      title: '文件编号',
      dataIndex: 'fileCode',

      align: 'center',
      sorter: true,
      width: 200,
    },
    {
      title: '文件名称',
      dataIndex: 'fileName',
      align: 'center',
      sorter: true,

      width: 200,
    },
    // {
    //   title: '版本号',
    //   dataIndex: 'version',
    //   align: 'center',
    //   sorter: true,
    //   width: 80,
    // },
    // {
    //   title: '启用状态',
    //   dataIndex: 'status',
    //   render: (text, record, _, action) => {
    //     return <div>{record.status == 1 ? '是' : '否'}</div>;
    //   },
    //   align: 'center',
    //   sorter: true,
    //   width: 80,
    // },
    // {
    //   title: '文件后缀',
    //   dataIndex: 'fileExtEndDate',
    //  align: 'center',sorter: true,
    // },
    // {
    //   title: '文件大小',
    //   dataIndex: 'fileSize',
    // },
    // {
    //   title: '备注',
    //   dataIndex: 'memo',
    // },
    {
      title: '上传人', //表头显示的名称
      search: false,
      dataIndex: 'createName',
      align: 'center',
      sorter: true,
      width: 100,
    },
    {
      title: '上传日期', //表头显示的名称
      search: false,
      dataIndex: 'createTime',

      align: 'center',
      sorter: true,
      width: 100,
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      align: 'center',
      width: 140,
      render: (text, record, _, action) => [
        <a
          key="downloadKey"
          onClick={() => {
            downloadFile({ standFileId: record.id }).then((res) => {
              const aLink = document.createElement('a');
              document.body.appendChild(aLink);
              aLink.style.display = 'none';
              aLink.href = window.URL.createObjectURL(res);
              aLink.setAttribute('download', `${record.fileName}`);
              aLink.click();
              document.body.removeChild(aLink);
            });
          }}
        >
          下载
        </a>,
        <a
          key="deleteKey"
          hidden={thisstate !== 0}
          onClick={() => {
            Modal.confirm({
              title: '删除',
              content: '确定要删除吗',
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                await delStandFileInfo({ id: record.id });
                actionRef.current.reload();
              },
            });
          }}
        >
          删除
        </a>,
        // <a
        //   key="useKey"
        //   onClick={async () => {
        //     if (record.status == '1') {
        //       message.warning('当前BOM已启用');
        //     }
        //     if (record.status == '-1') {
        //       const fileinfoparams = {
        //         category: record.category,
        //         standFileInfoId: record.id,
        //         standTypeId: record.standTypeId,
        //         status: '1',
        //       };
        //       console.log(fileinfoparams);
        //       const result = await switchStandFileInfo(fileinfoparams);
        //       if (result != null) {
        //         message.success('启用成功');
        //         actionRef.current.reload();
        //       }
        //     }
        //   }}
        // >
        //   启用
        // </a>,
        // <a
        //   key="nonuseKey"
        //   onClick={async () => {
        //     if (record.status == '-1') {
        //       message.warning('当前BOM已禁用');
        //     }
        //     if (record.status == '1') {
        //       const fileinfoparams = {
        //         category: record.category,
        //         standFileInfoId: record.id,
        //         standTypeId: record.standTypeId,
        //         status: '-1',
        //       };
        //       console.log(fileinfoparams);
        //       const result = await switchStandFileInfo(fileinfoparams);
        //       if (result != null) {
        //         message.success('禁用成功');
        //         actionRef.current.reload();
        //       }
        //     }
        //   }}
        // >
        //   禁用
        // </a>,
      ],
    },
  ];
  const handleSubmit = async () => {
    setConfirmLoading(true);
    // if (formTitle == '上传BOM附件') {
    //   form.validateFields((err, values) => {
    //     if (err) {
    //       message.useMessage().open({
    //         type: 'error',
    //         content: '有未填项！',
    //       });
    //     } else {
    //       console.log('上传附件结果：', values);
    //     }
    //   });
    //   .then(async () => {
    //     const res = {
    //       ...form.getFieldsValue(),
    //       standTypeCode: thisstandTypeCode,
    //       standTypeDesc: thisstandTypeDesc,
    //       standTypeId: thisstandid,
    //       standTypeName: thisstandname,
    //     };
    //     const formData = new window.FormData();
    //     formData.append('file', file);
    //     res.file = formData;
    //     res.category = 'BOM';
    //     console.log(res);
    //     const result = await uploadStandFileInfoBom(res);
    //     if (result != null) {
    //       message.success('添加成功');
    //       form.resetFields();
    //     }
    //     setConfirmLoading(false);
    //     setModalVisit(false);
    //     actionRef.current.reload();
    //   })
    //   .catch(() => {
    //     setConfirmLoading(false);
    //   });
    // }
    if (formTitle == '上传BOM附件') {
      form
        .validateFields()
        .then(async () => {
          const res = {
            ...form.getFieldsValue(),
            standTypeCode: thisstandTypeCode,
            standTypeDesc: thisstandTypeDesc,
            standTypeId: thisstandid,
            standTypeName: thisstandname,
          };
          const formData = new window.FormData();
          res.file.fileList.map((file) => {
            formData.append('file', file.originFileObj);
          });
          res.file = formData;
          res.category = 'BOM';
          console.log(res);
          const result = await uploadStandFileInfoBom(res);
          if (result != null) {
            message.success('添加成功');
            form.resetFields();
          }
          setConfirmLoading(false);
          setModalVisit(false);
          actionRef.current.reload();
        })
        .catch(() => {
          setConfirmLoading(false);
        });
    }
  };

  const getproductInfo = async () => {
    // 获取文件类型
    const gettype = await getStandFileType(null);
    const productfiletype: any[] = [];
    gettype.data.map((item: any, index: any) => {
      productfiletype.push({ value: item, label: item });
    });
    setoptionsstandfile(productfiletype);
  };

  const onFilesChange = async (file) => {
    setFile(file);
  };

  const beforeUpload = (file) => {
    setFile(file);
    return false;
  };

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <ProTable
        headerTitle="标准柜体BOM列表"
        scroll={{ x: 1500, y: 300 }}
        actionRef={actionRef} //用于触发刷新操作等，看api
        rowKey="id" //表格行 key 的取值，可以是字符串或一个函数
        formRef={ref}
        search={false}
        toolBarRender={(action, { selectedRows }) => [
          <>
            <Button
              key="bombutton"
              icon={<DownloadOutlined />}
              onClick={() => {
                downloadStandardBom(null).then((res) => {
                  const aLink = document.createElement('a');
                  document.body.appendChild(aLink);
                  aLink.style.display = 'none';
                  aLink.href = window.URL.createObjectURL(res);
                  aLink.setAttribute('download', `BOM导入模板.xls`);
                  aLink.click();
                  document.body.removeChild(aLink);
                });
              }}
              type="primary"
            >
              下载BOM模板
        </Button>
            {/*            <Button
                 key="button"
                 icon={<ArrowLeftOutlined />}
                 onClick={() => {
                  history.push('/design/standProduct');
                 }}
                 type="primary"
               >
                 返回
               </Button>, */}
            <Button
              key="button"
              icon={<UploadOutlined />}
              hidden={thisstate !== 0}
              onClick={() => {
                setCreateOrUpdate(true);
                setFormTitle('上传BOM附件');
                setModalVisit(true);
              }}
              type="primary"
            >
              上传
          </Button>
          </>
        ]}
        request={async (params = {}, sort, filter) => {
          const res = { ...params };
          const sorters = sortTran(sort);
          const filters = filterTranNew(res);
          const pageEntity = {
            standTypeId: thisstandid,
            pageEntity: {
              current: 1,
              pageSize: 6,
              filters: filters,
              sorters: sorters,
            },
            category: 'BOM',
          };
          const result = await getStandFileInfoByStandTypeIdAndCategoryPage(pageEntity);
          const newResult = result.data.content.filter((item: any, index: any) => {
            if (index === 0) {
              item.createTime = item.createTime.split(' ')[0];
              return item;
            }
          });
          console.log('bom列表：', result.data.content);
          getproductInfo();
          // result.data.content.map((item: any, index: any) => {
          //   if (item.status==1){
          //     setbomisuse(true);//如果有正在启用的BOM
          //   }
          // });
          // if (bomisuse==false){
          //   message.warning('当前没有正在启用的BOM');
          // }
          return {
            data: newResult,
            total: result.data.totalElements,
            success: result.success,
          };
        }}
        columns={columns}
        rowSelection={{}}
      />
      <Modal
        title={formTitle}
        visible={modalVisit}
        onOk={handleSubmit}
        confirmLoading={confirmLoading}
        onCancel={() => setModalVisit(false)}
      >
        <Form
          name="wrap"
          labelCol={{ flex: '110px' }}
          labelAlign="left"
          labelWrap
          form={form}
          wrapperCol={{ flex: 1 }}
          colon={false}
          initialValues={{ category: 'BOM' }}
        >
          <Form.Item label="id" name="id" hidden={true}>
            <Input />
          </Form.Item>
          {/* <Form.Item
            label="柜体类型"
            name="standTypeDesc"
            rules={[{ required: true, message: '请选择柜体类型!' }]}
          >
             <Select
              placeholder="请选择柜体类型"
              disabled  //不可更改
              onChange={(value, label) => {  }}
              options={optionsTypeDesc}
            />
          </Form.Item>
          <Form.Item
            label="柜体编号"
            name="standTypeCode"
            rules={[{ required: true, message: 'Please input your standTypeCode!' }]}
          >
            <Input disabled/>
          </Form.Item> */}

          {/* <Form.Item
            label="文件类别"
            name="category"
            rules={[{ required: true, message: '请选择文件类别!' }]}
          >
            <Select
              defaultValue="BOM"
              onChange={() => {}}
              options={[{ value: 'BOM', label: 'BOM' }]}
            />
          </Form.Item> */}
          <Row justify={'space-between'}>
            <Col span={14}>
              <Form.Item
                hidden={true}
                label="文件类别"
                name="category"
                rules={[{ required: true, message: '请选择文件类别!' }]}
              >
                <Select options={[{ value: 'BOM', label: 'BOM' }]} />
              </Form.Item>
            </Col>
          </Row>
          <Row justify={'center'}>
            <Col span={14}>
          <Form.Item
            label="上传文件"
            name="file"
            rules={[{ required: true, message: '请上传文件!' }]}
          >
            {/* <div key={Math.random()}> */}
            <Upload
              file-list="fileList"
              customRequest={onFilesChange} //通过覆盖默认的上传行为，可以自定义自己的上传实现
              showUploadList={true}
              beforeUpload={beforeUpload}
              multiple={true}
            >
              <Button className="standProduct_UploadStyle" icon={<UploadOutlined />}>
                上传文件
              </Button>
            </Upload>
            {/* </div> */}
          </Form.Item>
          </Col>
          </Row>
          {/* <Form.Item label="备注" name="memo">
            <Input />
          </Form.Item> */}
        </Form>
      </Modal>
    </PageHeaderWrapper>
  );
};
export default StandFileInfoBOM;
